<?php

!defined('IN') && exit('Access denied');

$opt = $_REQUEST['opt'];
$allow = array('list','add','modi');
$opt = in_array($opt,$allow) ? $opt : $allow['0'];

if (in_array($opt,array('modi','add'))) {
    if ($opt == 'modi') {
        $fp = $_ENV['db']->fetch("SELECT * FROM fapiao WHERE fid = '".(int)$_GET['fid']."'");
        if (!$fp) exit('x');
        $template->fp = $fp;
    }
    if (POST && AJAX) {
        $data = validate();
        switch ($opt) {
            case 'modi':
                $sql = buildSql($data);
                $sql = "UPDATE fapiao {$sql} WHERE fid = '".(int)$_GET['fid']."'";
            break;

            case 'add':
                $data['uid'] = $_G['cid'];
                $sql = buildSql($data);
                $sql = "INSERT INTO fapiao {$sql}";
            break;
        }

        $_ENV['db']->runSql($sql);

        outputJson(1,'操作成功');
    }
    $template->my_page = "front/fapiao_modi";
}

if ($opt == 'list') {
    $flist = $_ENV['db']->fetchAll("SELECT * FROM fapiao WHERE uid = '{$_G['cid']}'");
    $template->flist = $flist;
    $template->my_page = 'front/fapiao_list';
}

function validate() {
    $data = getRequests(array('name','nr'));

    if (count($data) != 2) {
        outputJson(0,'请补全信息');
    }

    $length = strlen($data['name']);
    if ($length < 1 || $length > 100) {
        outputJson(0,'发票名称长度应该为1到10位字符');
    }

    /*$length = strlen($data['tt']);
    if ($length < 1 || $length > 100) {
        outputJson(0,'发票抬头长度应该为1到10位字符');
    }*/

    $length = strlen($data['nr']);
    if ($length < 1 || $length > 100) {
        outputJson(0,'发票内容长度应该为1到10位字符');
    }

    return $data;
}